package no58;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/5/22 11:24
 * I 翻转单词顺序
 * https://leetcode.cn/problems/fan-zhuan-dan-ci-shun-xu-lcof/
 */
public class Solution {

    // 双指针方式
    public String reverseWords01(String s) {
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }

    // 使用库函数方式
    public String reverseWords02(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        String[] words = s.split(" ");
        StringBuilder res = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            if ("".equals(words[i])){
                continue;
            }
            res.append(words[i] + " ");
        }
        return res.toString().trim();
    }
}
